import {
  Button,
  Icon,
  Tooltip,
  KeyboardKey,
  TextField,
  IndexTable,
  LegacyCard,
  useIndexResourceState,
  useSetIndexFiltersMode,
  Text,
  Badge,
  Link,
  IndexFilters,
  RangeSlider,
  ChoiceList,
  IndexFiltersMode,
} from "@shopify/polaris";

import type { IndexFiltersProps, TabProps } from "@shopify/polaris";

import React from "react";
import {
  ChevronDownMinor,
  CaretUpMinor,
  ReplayMinor,
  TemplateMinor,
  FilterMajor,
  CircleInformationMajor,
  ExtendMinor,
  SearchMajor,
} from "@shopify/polaris-icons";
import styled from "./index.module.less";
import { useState, useCallback } from "react";

import MoBan from "./components/MoBan";

import { useNavigate } from "react-router-dom";

const App = () => {
  const navigate = useNavigate();
  const [sxtzk, setSxtjzk] = useState(false);

  const [value, setValue] = useState("");

  const handleChange = useCallback((newValue: any) => setValue(newValue), []);

  const orders = [
    {
      id: "1020",
      order: "#1020",
      date: "Cook",
      customer: 1,
      total: "China",
      paymentStatus: 0,
      fulfillmentStatus: 0.01,
    },
    {
      id: "1019",
      order: "#1019",
      date: "Petter",
      customer: 0,
      total: "China",
      paymentStatus: 0,
      fulfillmentStatus: 0.12,
    },
    {
      id: "1018",
      order: "#1018",
      date: "Mr Green",
      customer: 1,
      total: "China",
      paymentStatus: 0,
      fulfillmentStatus: 0.21,
    },
  ];

  const resourceName = {
    singular: "order",
    plural: "orders",
  };

  const { selectedResources, allResourcesSelected, handleSelectionChange } =
    useIndexResourceState(orders);

  const rowMarkup = orders.map(
    (
      { id, order, date, customer, total, paymentStatus, fulfillmentStatus },
      index
    ) => (
      <IndexTable.Row
        id={id}
        key={id}
        selected={selectedResources.includes(id)}
        position={index}
        subdued
      >
        <IndexTable.Cell>
          <Link dataPrimaryLink url={"customers/5669544886335"}>
            <div className={styled.LINK}>{date}</div>
          </Link>
        </IndexTable.Cell>
        <IndexTable.Cell>
          {
            [<Badge>未订阅</Badge>, <Badge status="success">已订阅</Badge>][
              customer
            ]
          }
        </IndexTable.Cell>
        <IndexTable.Cell>{total}</IndexTable.Cell>
        <IndexTable.Cell>{paymentStatus}订单</IndexTable.Cell>
        <IndexTable.Cell>￥{fulfillmentStatus}</IndexTable.Cell>
      </IndexTable.Row>
    )
  );

  const promotedBulkActions = [
    {
      content: "批量编辑",
      onAction: () => console.log("Todo: 批量编辑"),
    },
  ];
  const bulkActions = [
    {
      content: "合并客户",
      onAction: () => console.log("Todo: 合并客户"),
    },
    {
      content: "添加标签",
      onAction: () => console.log("Todo: 添加标签"),
    },
    {
      content: "删除标签",
      onAction: () => console.log("Todo: 删除标签"),
    },
    {
      content: "添加到公司",
      onAction: () => console.log("Todo: 添加到公司"),
    },
    {
      content: "删除客户",
      onAction: () => console.log("Todo: 删除客户"),
    },
  ];

  //indexfilters
  const [selected, setSelected] = useState(0);
  const sleep = (ms: number) =>
    new Promise((resolve) => setTimeout(resolve, ms));
  const [itemStrings, setItemStrings] = useState([
    "All",
    "Unpaid",
    "Open",
    "Closed",
    "Local delivery",
    "Local pickup",
  ]);
  const deleteView = (index: number) => {
    const newItemStrings = [...itemStrings];
    newItemStrings.splice(index, 1);
    setItemStrings(newItemStrings);
    setSelected(0);
  };

  const duplicateView = async (name: string) => {
    setItemStrings([...itemStrings, name]);
    setSelected(itemStrings.length);
    await sleep(1);
    return true;
  };

  const tabs: TabProps[] = itemStrings.map((item, index) => ({
    content: item,
    index,
    onAction: () => {},
    id: `${item}-${index}`,
    isLocked: index === 0,
    actions:
      index === 0
        ? []
        : [
            {
              type: "rename",
              onAction: () => {},
              onPrimaryAction: async (value: string): Promise<boolean> => {
                const newItemsStrings = tabs.map((item, idx) => {
                  if (idx === index) {
                    return value;
                  }
                  return item.content;
                });
                await sleep(1);
                setItemStrings(newItemsStrings);
                return true;
              },
            },
            {
              type: "duplicate",
              onPrimaryAction: async (value: string): Promise<boolean> => {
                await sleep(1);
                duplicateView(value);
                return true;
              },
            },
            {
              type: "edit",
            },
            {
              type: "delete",
              onPrimaryAction: async () => {
                await sleep(1);
                deleteView(index);
                return true;
              },
            },
          ],
  }));

  const sortOptions: IndexFiltersProps["sortOptions"] = [
    {
      label: "最后更新时间",
      value: "LastTimeUpdate asc",
      directionLabel: "由旧到新",
    },
    {
      label: "最后更新时间",
      value: "LastTimeUpdate desc",
      directionLabel: "由新到旧",
    },
    { label: "消费金额", value: "Monetary asc", directionLabel: "最低到最高" },
    { label: "消费金额", value: "Monetary desc", directionLabel: "最高到最低" },
    {
      label: "总订单量",
      value: "Totalorder asc",
      directionLabel: "最低到最高",
    },
    {
      label: "总订单量",
      value: "Totalorder desc",
      directionLabel: "最高到最低",
    },
    {
      label: "上次订购日期",
      value: "lastordertime asc",
      directionLabel: "由旧到新",
    },
    {
      label: "上次订购日期",
      value: "lastordertime desc",
      directionLabel: "由新到旧",
    },
    {
      label: "首单日期",
      value: "firstordertime asc",
      directionLabel: "由旧到新",
    },
    {
      label: "首单日期",
      value: "firstordertime desc",
      directionLabel: "由新到旧",
    },
    {
      label: "添加为客户日期",
      value: "Ascustomertime asc",
      directionLabel: "由旧到新",
    },
    {
      label: "添加为客户日期",
      value: "Ascustomertime desc",
      directionLabel: "由新到旧",
    },
    {
      label: "上次弃单日期",
      value: "lastAbandonedtime asc",
      directionLabel: "由旧到新",
    },
    {
      label: "上次弃单日期",
      value: "lastAbandonedtime desc",
      directionLabel: "由新到旧",
    },
  ];
  //排序默认选项
  const [sortSelected, setSortSelected] = useState(["LastTimeUpdate asc"]);
  const { mode, setMode } = useSetIndexFiltersMode(IndexFiltersMode.Filtering);
  const onHandleCancel = () => {};

  const [accountStatus, setAccountStatus] = useState<string[] | undefined>(
    undefined
  );
  const [moneySpent, setMoneySpent] = useState<[number, number] | undefined>(
    undefined
  );
  const [taggedWith, setTaggedWith] = useState("");

  const handleAccountStatusChange = useCallback(
    (value: string[]) => setAccountStatus(value),
    []
  );
  const handleMoneySpentChange = useCallback(
    (value: [number, number]) => setMoneySpent(value),
    []
  );
  const handleTaggedWithChange = useCallback(
    (value: string) => setTaggedWith(value),
    []
  );

  const filters = [
    {
      key: "accountStatus",
      label: "Account status",
      filter: (
        <ChoiceList
          title="Account status"
          titleHidden
          choices={[
            { label: "Enabled", value: "enabled" },
            { label: "Not invited", value: "not invited" },
            { label: "Invited", value: "invited" },
            { label: "Declined", value: "declined" },
          ]}
          selected={accountStatus || []}
          onChange={handleAccountStatusChange}
          allowMultiple
        />
      ),
      shortcut: true,
    },
    {
      key: "taggedWith",
      label: "Tagged with",
      filter: (
        <TextField
          label="Tagged with"
          value={taggedWith}
          onChange={handleTaggedWithChange}
          autoComplete="off"
          labelHidden
        />
      ),
      shortcut: true,
    },
    {
      key: "moneySpent",
      label: "Money spent",
      filter: (
        <RangeSlider
          label="Money spent is between"
          labelHidden
          value={moneySpent || [0, 500]}
          prefix="$"
          output
          min={0}
          max={2000}
          step={1}
          onChange={handleMoneySpentChange}
        />
      ),
    },
  ];

  const handleFiltersQueryChange = useCallback(
    (value: string) => setQueryValue(value),
    []
  );

  const [queryValue, setQueryValue] = useState("");

  const handleAccountStatusRemove = useCallback(
    () => setAccountStatus(undefined),
    []
  );
  const handleMoneySpentRemove = useCallback(
    () => setMoneySpent(undefined),
    []
  );
  const handleTaggedWithRemove = useCallback(() => setTaggedWith(""), []);
  const handleQueryValueRemove = useCallback(() => setQueryValue(""), []);
  const handleFiltersClearAll = useCallback(() => {
    handleAccountStatusRemove();
    handleMoneySpentRemove();
    handleTaggedWithRemove();
    handleQueryValueRemove();
  }, [
    handleAccountStatusRemove,
    handleMoneySpentRemove,
    handleQueryValueRemove,
    handleTaggedWithRemove,
  ]);

  //模板
  const [sheetActive, setSheetActive] = useState(false);

  return (
    <div className={styled.box}>
      <div className={styled.context}>
        <div className={styled.top}>
          <div className={styled.topLeft}>客户</div>
          <div className={styled.topRight}>
            <div>
              <Button size="slim">导出</Button>
            </div>
            <div className={styled.middleBtn}>
              <Button size="slim">导入</Button>
            </div>
            <div>
              <Button
                size="slim"
                primary
                onClick={() => {
                  navigate("/customers/new");
                }}
              >
                添加客户
              </Button>
            </div>
          </div>
        </div>
        <div className={styled.selection}>
          {!sxtzk && (
            <div className={styled.Card}>
              <div className={styled.CardLeft}>
                <div>3位客户</div>
                <div className={styled.div}>100%客户群</div>
              </div>
              <div
                className={styled.SXTJ}
                onClick={() => {
                  setSxtjzk(true);
                }}
              >
                <div>添加筛选条件</div>
                <div>
                  <Icon source={ChevronDownMinor}></Icon>
                </div>
              </div>
            </div>
          )}
          {sxtzk && (
            <div className={styled.CardBOX}>
              <div className={styled.Card1}>
                <div className={styled.CardLeft1}>
                  <div>3位客户</div>
                  <div className={styled.div}>100%客户群</div>
                </div>
                <div className={styled.SXTJ1}>
                  <div className={styled.SXTJ1LEFT}>
                    <div className={styled.SXTJ1LEFT1}>
                      <div className={styled.IcoNtip}>
                        <Tooltip
                          content={
                            <div className={styled.TOOPltip}>
                              <div style={{ textAlign: "center" }}>撤销</div>
                              <div>
                                <KeyboardKey>Ctrl</KeyboardKey>
                                <KeyboardKey>Z</KeyboardKey>
                              </div>
                            </div>
                          }
                        >
                          <div>
                            <Icon source={ReplayMinor}></Icon>
                          </div>
                        </Tooltip>
                      </div>
                    </div>
                    <div className={styled.IcoNtip}>
                      <Tooltip
                        content={
                          <div className={styled.TOOPltip}>
                            <div style={{ textAlign: "center" }}>恢复</div>
                            <div>
                              <KeyboardKey>Ctrl</KeyboardKey>
                              <KeyboardKey>Y</KeyboardKey>
                            </div>
                          </div>
                        }
                      >
                        <div className={styled.PADDING}>
                          <Icon source={ReplayMinor}></Icon>
                        </div>
                      </Tooltip>
                    </div>
                  </div>
                  <div className={styled.MB1}>
                    <div
                      className={styled.MBSXQ1}
                      onClick={() => {
                        setSheetActive(!sheetActive);
                      }}
                    >
                      <div>
                        <Icon source={TemplateMinor}></Icon>
                      </div>
                      <div>模板</div>
                    </div>
                  </div>
                  <div className={styled.MB}>
                    <div className={styled.MBSXQ2}>
                      <div>
                        <Icon source={FilterMajor}></Icon>
                      </div>
                      <div>筛选器</div>
                    </div>
                  </div>
                  <div
                    className={styled.SXTJ1RIGHT}
                    onClick={() => {
                      setSxtjzk(false);
                    }}
                  >
                    <div className={styled.SXTJ1RIGHTB}>
                      <Tooltip content="关闭编译器">
                        <Icon source={CaretUpMinor}></Icon>
                      </Tooltip>
                    </div>
                  </div>
                </div>
              </div>
              <div className={styled.CardMiddle}>
                <textarea className={styled.textarea}>
                  <pre></pre>
                </textarea>
                {/* <div dangerouslySetInnerHTML={{ __html: value }}></div> */}
              </div>
              <div className={styled.Cardfooter}>
                <div>
                  {value && (
                    <div className={styled.CDJXZ}>
                      <div>
                        <Icon source={CircleInformationMajor}></Icon>
                      </div>
                      <div>进行中</div>
                    </div>
                  )}
                </div>
                <div className={styled.CDYY}>
                  <div className={styled.CDbtn}>
                    {value && (
                      <div style={{ color: "black" }}>
                        <Button size="slim">放弃</Button>
                      </div>
                    )}
                  </div>
                  <div>
                    <Button size="slim">应用</Button>
                  </div>
                </div>
              </div>
            </div>
          )}
        </div>
        <div className={styled.footer}>
          <div className={styled.FTRtop}>
            <div className={styled.TEXT}>
              <TextField
                label=""
                value={value}
                prefix={<Icon source={SearchMajor}></Icon>}
                onChange={handleChange}
                autoComplete="off"
                borderless
                placeholder="搜索客户"
              />
            </div>
          </div>
          <div>
            <div className={styled.indexFilters}>
              <IndexFilters
                onQueryChange={handleFiltersQueryChange}
                onQueryClear={() => {}}
                selected={selected}
                onClearAll={handleFiltersClearAll}
                sortOptions={sortOptions}
                sortSelected={sortSelected}
                queryPlaceholder="Searching in all"
                onSort={setSortSelected}
                cancelAction={{
                  onAction: onHandleCancel,
                  disabled: false,
                  loading: false,
                }}
                tabs={tabs}
                filters={filters}
                mode={mode}
                setMode={setMode}
                hideFilters
              />
            </div>
            <IndexTable
              resourceName={resourceName}
              itemCount={orders.length}
              selectedItemsCount={
                allResourcesSelected ? "All" : selectedResources.length
              }
              onSelectionChange={handleSelectionChange}
              // hasMoreItems
              bulkActions={bulkActions}
              promotedBulkActions={promotedBulkActions}
              headings={[
                {
                  title: <div className={styled.HEADINGS}>客户姓名</div>,
                  id: "1",
                },
                {
                  title: <div className={styled.HEADINGS}>电子邮件订阅</div>,
                  id: "2",
                },
                { title: <div className={styled.HEADINGS}>地点</div>, id: "3" },
                {
                  title: <div className={styled.HEADINGS}>订单量</div>,
                  id: "4",
                },
                {
                  title: <div className={styled.HEADINGS}>消费金额</div>,
                  id: "5",
                },
              ]}
              // sortable={[true, true, true, true, true, true, false, true]}
              // selectable
            >
              {rowMarkup}
            </IndexTable>
          </div>
        </div>
        <div className={styled.foterZ}>
          详细了解
          <Link>客户</Link>
        </div>
      </div>
      {/* 模板组件 */}
      {/* {MoBanshow && <MoBan setMoBanshow={setMoBanshow} />} */}
      {sheetActive && (
        <MoBan
          sheetActive={sheetActive}
          setSheetActive={setSheetActive}
          setValue={setValue}
        />
      )}
      {/* 模板组件 */}
    </div>
  );
};

export default App;
